package show.me.the.money.util.exp.standard;

import java.util.HashMap;
import java.util.List;

import show.me.the.money.util.context.Context;
import show.me.the.money.util.exp.Expression;

@SuppressWarnings("unchecked")
public class REF extends Expression {

	public Object run(List lsExp, Context ctx) {
		try {
			String name = (String)lsExp.get(1);
			boolean valueRef = false;
			if (name.startsWith("%")) {
				name = name.substring(1);
				valueRef = true;
			}
			HashMap<String,Object> arg = null;
			int size = lsExp.size();
			if (size > 2) {
				if (size == 4) {
					arg = (HashMap<String,Object>)lsExp.get(3);
				}
				if (size == 3) {
					if (!valueRef) {
						arg = (HashMap<String,Object>)lsExp.get(2);
					}
				}
			}
			return ctx.get(name, arg);
		} 
		catch (Exception e) {
			logger.fatal("run JSONException:", e);
		}
		return null;
	}

	public String toString(List lsExp, Context ctx) {
		try {
			String name = (String)lsExp.get(1);
			if (name.startsWith("%")) {
				name = (String)run(lsExp, ctx);
				int size = lsExp.size();
				if (!(size > 2 && lsExp.get(size - 1).equals("d"))) {
					name = "'" + name + "'";
				}
			}
			return name;
		} catch (Exception e) {
			logger.fatal("toString JSONException:", e);
		}
		return "";
	}

}
